﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
using System.Xml.Linq;
using System.Threading;
using System.Globalization;
using Nivdal.AuxCode;

namespace Nivdal
{
    public partial class coach : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            string CoachId = "";
            // security - for not confirmed or anonymous users
            //if (!HttpContext.Current.User.Identity.IsAuthenticated)
            //    Response.Redirect("~/Default.aspx");
            OnlineUser ou = (OnlineUser)Session["User"];
            //if (ou.TeamId == "Null")
            //    Response.Redirect("~/GeneralMessage.aspx?MessageString=M74ggdizz5wfeh");
            //else
            //    this.TeamIdHiddenField.Value = ou.TeamId;

            if (Request.QueryString["ConfirmMessage"] != null)
            {
                this.MessageLabel.Text = Request.QueryString["ConfirmMessage"].ToString();
            }
            ReleaseButton.Attributes.Add("onclick", "javascript:if(confirm('" + Resources.Resource.Coach_SureReleaseCoach + "')== false) return false;");
            
            if (Request.QueryString["Id"] != null)
            {
                CoachId = Request.QueryString["Id"].ToString();
                CoachIdHiddenField.Value = CoachId;
            }
            else        
                Response.Redirect("GeneralMessage.aspx?MessageString=Z4331EOTHJA");
            
            
            if (!IsPostBack)
            {
                this.ShowCoachDetailsSqlDataSource.SelectParameters.Add("CoachId", CoachId);
                this.ShowCoachDetailsSqlDataSource.SelectParameters.Add("Language", ou.Language);
                this.CoachTransfersDataSource.SelectParameters.Add("CoachId", CoachId);
            }

            if (HttpContext.Current.User.Identity.IsAuthenticated)
                this.ReleaseButton.Visible = (IsUserCoachOwner(ou.UserId, CoachId));
            else
                this.ReleaseButton.Visible = false;

            if (GND.ReadNivdalBoolData("@CoachId", "Nivdal_TrainingIsCoachTransferlisted", CoachId) && HttpContext.Current.User.Identity.IsAuthenticated)
            {
                if (!IsPostBack)
                {
                    this.ShowFreeCoachInfoSqlDataSource.SelectParameters.Add("CoachId", CoachId);
                    this.ShowFreeCoachInfoSqlDataSource.SelectParameters.Add("Language", ou.Language);
                    this.ConditionalBidOnCoachDataSource.SelectParameters.Add("CoachId", CoachId);
                    this.ConditionalBidOnCoachDataSource.SelectParameters.Add("TeamId", ou.TeamId);
                }
                this.BidOnCoachPanel.Visible = true;

                //this.CoachBidLinkButton.Visible = true;
                //this.CoachBidLinkButton.PostBackUrl = "~/BidOnCoach.aspx?CoachId=" + CoachId;
            }
           

            string CoachName = (this.CoachFormView.FindControl("NameLabel") as Label).Text;
            this.PageNameLabel.Text = Resources.Resource.Coach_PageNameLabel + " " + CoachName;
            this.Title = Resources.Resource.Default_PageTitle + ", " + Resources.Resource.coach_PageTitle + ": " + CoachName;
            this.MessagePanel.Visible = ((this.MessageLabel.Text.Length > 0) || (this.ErrorLabel.Text.Length > 0));
        }


        protected bool IsUserCoachOwner(string UserId, string CoachId)
        {
            bool ReturnValue = false;
            string conn = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            System.Data.SqlClient.SqlConnection strConnection = new System.Data.SqlClient.SqlConnection(conn);
            string StrSQL = "Nivdal_TrainingUserIsCoachOwner ";
            System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(StrSQL, strConnection);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@UserId", UserId));
            cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@CoachId", CoachIdHiddenField.Value));
            strConnection.Open();
            try
            {
                ReturnValue = Convert.ToBoolean(cmd.ExecuteScalar());

                //MessageLabel.Text = ReturnValue.ToString();
            }
            catch { }
            //catch (Exception SQLDBException)
            //{
            //    //this.MessageLabel.ForeColor = System.Drawing.Color.Red;
            //    //MessageLabel.Text = Convert.ToString(SQLDBException);
            //}

            finally
            {
                strConnection.Close();
            }
            return ReturnValue;

        }

        protected void ReleaseButton_Click(object sender, EventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];
            if (GND.ReadNivdalBoolData("@UserId", "Nivdal_TrainingReleaseCoach", ou.UserId))
            {
                Response.Redirect("~/Coach.aspx?Id=" + CoachIdHiddenField.Value + "&ConfirmMessage=" + Resources.Resource.Coach_CoachReleased);
            }

        }

        protected void BookmarkButton_Click(object sender, EventArgs e)
        {
            OnlineUser ou = (OnlineUser)Session["User"];

            string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            System.Data.IDbConnection dbConnection = new System.Data.SqlClient.SqlConnection(conn);
            System.Data.IDbCommand dbCommand = new System.Data.SqlClient.SqlCommand();
            dbCommand.CommandText = "Nivdal_BookmarkCoach";
            dbCommand.CommandType = CommandType.StoredProcedure;
            dbCommand.Connection = dbConnection;

            SqlParameter dbParam_UserId = new SqlParameter();
            dbParam_UserId.ParameterName = "@UserId";
            dbParam_UserId.Value = ou.UserId;
            dbParam_UserId.DbType = DbType.String;
            dbCommand.Parameters.Add(dbParam_UserId);

            SqlParameter dbParam_BookmarkedPlayer = new SqlParameter();
            dbParam_BookmarkedPlayer.ParameterName = "@BookmarkedCoach";
            dbParam_BookmarkedPlayer.Value = CoachIdHiddenField.Value;
            dbParam_BookmarkedPlayer.DbType = DbType.String;
            dbCommand.Parameters.Add(dbParam_BookmarkedPlayer);

            SqlParameter dbParam_Answer = new SqlParameter();
            dbParam_Answer.ParameterName = "@Answer";
            dbParam_Answer.Value = "";
            dbParam_Answer.DbType = DbType.String;
            dbParam_Answer.Direction = ParameterDirection.Output;
            dbParam_Answer.Size = 64;
            dbCommand.Parameters.Add(dbParam_Answer);

            try
            {

                dbConnection.Open();
                dbCommand.ExecuteScalar();
                Response.Redirect("Bookmarks.aspx?ConfirmNote=" + dbParam_Answer.Value.ToString());
            }
            //catch (Exception SQLDBException)
            //{
            //    //this.ErrorLabel.Text = Convert.ToString(SQLDBException);
            //}

            finally
            {
                dbConnection.Close();
            }

        }

        //public bool IsPremium()
        //{
        //    OnlineUser ou = (OnlineUser)Session["User"];
        //    return (ou.IsPremium);
        //}


        protected void BidButton_Click(object sender, EventArgs e)
        {
            String ReturnValue = "Error";
            OnlineUser ou = (OnlineUser)Session["User"];
            
            string NextPossibleBid = (this.FormView1.Row.FindControl("NextPossibleBidLabel") as Label).Text;

            string conn = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            System.Data.SqlClient.SqlConnection strConnection = new System.Data.SqlClient.SqlConnection(conn);
            string StrSQL = "Nivdal_BidOnCoach";
            System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(StrSQL, strConnection);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@CoachId", CoachIdHiddenField.Value));
            cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@UserId", ou.UserId));
            cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Bid", NextPossibleBid));

            strConnection.Open();
            try
            {
                ReturnValue = cmd.ExecuteScalar().ToString();
                Response.Redirect("~/Coach.aspx?Id=" + CoachIdHiddenField.Value + "&ConfirmMessage=" + ReturnValue);
            }
            catch { }
            finally
            {
                strConnection.Close();
            }
        }

        protected override void InitializeCulture()
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(ou.UICulture);
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ou.Culture);
        }

        protected string BidButtonOnClientClick(string cost)
        {
            return ("return confirm('" + Resources.Resource.coach_BidButtonOnClientClickPart1 + " " + cost +
                " " + Resources.Resource.coach_BidButtonOnClientClickPart2 + "')");
        }

        protected void BidTimerTick(object sender, EventArgs e)
        {
            try
            {
                FormView1.DataBind();
                (FormView1.FindControl("ConditionalBidFormView") as FormView).DataBind();
            }
            catch { }
        }

        protected void ConditionalBidItemCommand(object sender, FormViewCommandEventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];
            string Message = "";

            if (e.CommandName == "Delete")
            {
                GND.ExecNivdalSQL("ConditionalBidId", "Nivdal_RemoveConditionalBid", e.CommandArgument);
                Message = "Conditional bid deleted";
            }
            else if (e.CommandName == "Set")
            {
                FormView CondBidFormView = FormView1.FindControl("ConditionalBidFormView") as FormView;
                TextBox CondBidTextBox = CondBidFormView.FindControl("ConditionalBidTextBox") as TextBox;
                string CondBid = CondBidTextBox.Text;

                Message = GND.ReadNivdalStringData("CoachId", "TeamId", "ConditionalBidSum", "Language", "Nivdal_AddConditionalBidOnCoach", CoachIdHiddenField.Value,
                                               ou.TeamId, CondBid, ou.Language);
            }
            Response.Redirect("coach.aspx?Id=" + CoachIdHiddenField.Value + "&ConfirmMessage=" + Message);
        }

        protected string ParceNumber(object number)
        {
            string ReturnValue = number.ToString();

            try
            {
                ReturnValue = int.Parse(number.ToString()).ToString("N0");
            }
            catch { }

            return (ReturnValue);
        }

        protected bool IsPremium()
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            return ou.IsPremium;
        }
    }
}